package com.wy0924.filter;

import com.wy0924.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;

@WebFilter(urlPatterns = {"/userList.jsp"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断List集合是否为空
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        HttpSession session = servletRequest1.getSession();
        ServletContext servletContext = servletRequest1.getServletContext();
        ArrayList<User> userList = (ArrayList<User>) servletContext.getAttribute("userList");


        //空 跳回登陆界面
        if (userList == null) {
            HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
            servletResponse1.sendRedirect("./login.jsp");
        }
        //不为空
        else {
            //判断 session.getAttribute("user");是否为空
            User attribute = (User) session.getAttribute("user");
            if (attribute == null) {
                //空 跳回登陆界面
                HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
                servletResponse1.sendRedirect("./login.jsp");
            }else {
                //不为空
                //判断List集合是否包含 session.getAttribute("user");
                int i = userList.indexOf(attribute);
                //否 登陆失败 删除user
                if (i == -1) {
                    session.removeAttribute("user");
                    HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
                    servletResponse1.sendRedirect("./login.jsp");
                }
                //是 登录成功
                else {
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            }

        }

    }
}
